<template>
    <div class="branch">
        <div class="page-action-btn">
            <p-confirm-btn type="success" v-if="UIAuth._api_admin_branch_id_put && tableRow" @confirm="setDefault" msg="确定要设置吗？">设为默认</p-confirm-btn>
            <el-button type="primary" v-if="UIAuth._api_admin_branch_post" @click="showAdd()">添加部门机构</el-button>
            <el-button type="warning" v-if="UIAuth._api_admin_branch_put" @click="showEdit">修改</el-button>
            <p-confirm-btn @confirm="del" v-if="UIAuth._api_admin_branch_delete"></p-confirm-btn>
        </div>
        <div v-if="UIAuth._api_admin_branch_get">
            <p-table-tree ref="pTableTree" v-loading="loading" :data="dataList" :sub-height="134" :show-paginate="false" @row-click="rowClick" @row-dblclick="showEdit" @row-clear="rowClear"
                @selection-change="selectionChange">
                <el-table-column prop="branch_name" label="名称" min-width="200">
                    <template v-slot="{ row }">
                        <span class="branch-default-icon">
                            <span class="branch-default-icon-title">
                                {{ row.branch_name }}</span>
                            <span v-if="row.is_default == 1" class="branch-default-icon-icon">默</span>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="sort" label="排序" width="80"></el-table-column>
            </p-table-tree>
        </div>
        <p-el-dialog v-model="showDialog" top="10vh" :title="`${isEdit ? '修改' : '添加'}的部门机构`" width="500px" @close="dialogClose" @confirm="isEdit ? edit() : add()" :ok-text="isEdit ? '修改' : '添加'">
            <el-form :model="params" status-icon :rules="paramsRules" ref="elForm" label-width="120px">
                <el-form-item label="上级部门机构">
                    <branch-tree-select v-model="params.pid"></branch-tree-select>
                </el-form-item>
                <el-form-item label="名称" prop="branch_name">
                    <el-input v-model="params.branch_name" placeholder="部门机构名称"></el-input>
                </el-form-item>
                <div v-if="branchAuthOpen">
                    <el-form-item label="权限角色">
                        <div style="color: #b67676; font-size: 12px">
                            向上继承，上级拥有所有下级的权限角色
                        </div>
                        <div v-for="item in params.roles" :key="item.auth_group_id">
                            <el-form-item :label="getAuthGroupTitle(item.auth_group_id)" label-width="60px">
                                <el-select v-model="item.roles" placeholder="请选择权限角色" multiple style="width: 100%">
                                    <el-option v-for="rItem in authGroupGetRolesList(item.auth_group_id)" :key="rItem.id" :label="rItem.role_name" :value="rItem.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                    </el-form-item>
                </div>

                <el-form-item label="排序">
                    <el-input v-model="params.sort" placeholder="排序"></el-input>
                </el-form-item>
            </el-form>
        </p-el-dialog>
    </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref, toRefs } from "vue";
import { useStore } from "vuex";
import { IPaginate, defaultPaginate } from "@/lib/IApp";
import PElDialog from "@/components/PElDialog.vue";
import valid from "@/lib/valid";
import http from "@/lib/http/http";
import PConfirmBtn from "@/components/PConfirmBtn.vue";
import message from "@/lib/message";
import utils from "@/lib/utils";
import PTableTree from "@/components/PTableTree.vue";
import config from "@/config";
import TreeTool from "@/lib/TreeTool";
import BranchTreeSelect from "@/components/branch/BranchTreeSelect.vue";
const ParamsRules: any = {
    branch_name: [
        { required: true, message: "请输入部门机构名称", trigger: ["blur"] },
    ],
};
const defaultParams = { roles: [] };
/**
 * state 数据类型
 */
interface IState {
    branchAuthOpen: boolean;
    loading: boolean;
    dataList: any[]; // 数据列表
    showDialog: boolean; // 是否显示 添加编辑窗口
    isEdit: boolean; // 是否修改
    params: any; // http 请求参数
    paramsRules: any; // 参数校验
    tableRow: any; // 单选选择的行内容
    tableRows: any[]; // 多选选择的行内容
    search: any; // 查询条件
    rolesList: any[]; // 权限角色列表
    authGroupList: any[]; // 权限组列表
    oldPid: string; // 修改之前的pid
}
export default defineComponent({
    name: "Branch",
    components: { PElDialog, PConfirmBtn, PTableTree, BranchTreeSelect },
    setup() {
        const store = useStore();
        const { UIAuth, bodySize } = toRefs(store.state);
        const elForm = ref<any>();
        const pTableTree = ref<any>();
        const state = reactive<IState>({
            branchAuthOpen: config.branchAuthOpen,
            loading: false,
            dataList: [],
            showDialog: false,
            isEdit: false,
            params: {},
            paramsRules: ParamsRules,
            tableRow: null,
            tableRows: [],
            search: {},
            rolesList: [],
            authGroupList: [],
            oldPid: "",
        });
        const treeTool: TreeTool = new TreeTool();
        // 单击选中
        function rowClick(val: any) {
            state.tableRow = val.row;
        }
        // 取消选中
        function rowClear() {
            state.tableRow = null;
        }
        // 关闭添加修改窗口
        function dialogClose(showDialog: boolean = false) {
            state.params = utils.CopyNewObject(defaultParams);
            state.oldPid = "";
            state.isEdit = showDialog;
            state.showDialog = showDialog;
        }
        // 多选时触发
        function selectionChange(val: any[]): void {
            state.tableRows = val;
        }
        // 通过权限组ID获取 权限角色列表
        function authGroupGetRolesList(id: string): any[] {
            const res: any[] = [];
            for (const item of state.rolesList) {
                if (item.auth_group_id === id) {
                    res.push(item);
                }
            }
            return res;
        }
        // 获取权限组内容
        function getAuthGroupList() {
            state.loading = true;
            http.Get(`/auth-group/share-id`)
                .then((data) => {
                    const shareId = data;
                    http.Get(`/auth-group`)
                        .then((dataList) => {
                            state.authGroupList = [];
                            dataList.forEach((item: any) => {
                                if (item.id !== shareId) {
                                    state.authGroupList.push(item);
                                }
                            });
                        })
                        .catch((err) => false);
                })
                .catch((err) => false);
        }
        // 获取权限角色内容
        function getRolesList() {
            http.Get(`/roles`)
                .then((data) => {
                    state.rolesList = data;
                })
                .catch((err) => false);
        }
        // 获取权限组名称
        function getAuthGroupTitle(val: string): string {
            let label = "";
            for (const item of state.authGroupList) {
                if (item.id === val) {
                    label = item.title;
                    break;
                }
            }
            return label;
        }
        // 初始化 参数中的权限
        function initParamsRoles(oldData: any = null) {
            const rolesList = [];
            const temMap: Map<string, []> = new Map<string, []>();
            if (!utils.empty(oldData)) {
                for (const item of oldData) {
                    temMap.set(item.auth_group_id, item.roles);
                }
            }
            for (const item of state.authGroupList) {
                let roles = temMap.get(item.id);
                if (utils.empty(roles)) {
                    roles = [];
                }
                rolesList.push({ auth_group_id: item.id, roles });
            }
            state.params.roles = rolesList;
        }
        // 显示添加
        function showAdd(isChile: boolean = true) {
            let pId = "";
            if (state.tableRow != null) {
                pId = state.tableRow.id;
            }
            state.oldPid = pId;
            state.params = {
                pid: pId,
                roles: [],
                sort: 1,
            };
            initParamsRoles(null);
            state.isEdit = false;
            state.showDialog = true;
        }
        // 获取内容
        function getList() {
            state.loading = true;
            http.Get(`/branch`, state.search)
                .then((data) => {
                    state.dataList = treeTool.listToTree(data, "");
                    state.loading = false;
                })
                .catch((err) => (state.loading = false));
        }
        // 添加
        function add() {
            elForm.value.validate((ok: boolean) => {
                if (ok) {
                    http.Post("/branch", state.params)
                        .then((data) => {
                            if (utils.empty(state.dataList)) {
                                state.dataList = [data];
                            } else {
                                treeTool.add(state.dataList, data);
                            }
                            dialogClose();
                        })
                        .catch((err) => "");
                } else {
                    return false;
                }
            });
        }
        // 显示修改
        function showEdit() {
            if (state.tableRow == null) {
                message.error("请选择要修改的数据");
                return;
            }
            state.isEdit = true;
            state.params.branch_name = state.tableRow.branch_name;
            state.params.sort = state.tableRow.sort;
            initParamsRoles(state.tableRow.roles);
            state.oldPid = state.tableRow.pid;
            state.params.pid = state.tableRow.pid;
            state.params.id = state.tableRow.id;
            state.params.version = state.tableRow.version;
            state.showDialog = true;
        }
        // 修改
        function edit() {
            elForm.value.validate((ok: boolean) => {
                if (ok) {
                    http.Put("/branch", state.params)
                        .then((data) => {
                            treeTool.edit(state.dataList, data);
                            if (state.oldPid !== data.pid) {
                                let temData = treeTool.get(
                                    state.dataList,
                                    data.id
                                );
                                if (utils.empty(temData)) {
                                    temData = data;
                                }
                                treeTool.delete(state.dataList, data.id);
                                treeTool.add(state.dataList, temData);
                            }
                            dialogClose();
                        })
                        .catch((err) => "");
                } else {
                    return false;
                }
            });
        }
        //
        function setDefault() {
            if (state.tableRow == null) {
                message.error("请选择要设置的部门机构");
                return;
            }
            http.Put(`/branch/${state.tableRow.id}`)
                .then((data) => {
                    state.dataList.forEach((item, index) => {
                        if (item.id === state.tableRow.id) {
                            state.tableRow.is_default = 1;
                            state.dataList[index].default = 1;
                        } else {
                            state.dataList[index].default = 2;
                        }
                    });
                })
                .catch((err) => "");
        }
        // 删除
        function del() {
            const ids: string[] = [];
            if (state.tableRows.length === 0) {
                if (state.tableRow == null) {
                    message.error("请选择要删除的数据");
                    return;
                } else {
                    ids.push(state.tableRow.id);
                }
            }
            let isDelete = true;
            state.tableRows.forEach((item) => {
                if (!utils.empty(item.children) && item.children.length > 0) {
                    isDelete = false;
                    return;
                }
                ids.push(item.id);
            });
            if (!isDelete) {
                message.error("删除的【部门机构】中存在子部门机构");
                return;
            }
            message.loadingShow("删除中");
            http.Delete("/branch", { ids })
                .then((data) => {
                    treeTool.deletes(state.dataList, ids);
                    state.tableRow = null;
                    state.tableRows = [];
                    pTableTree.value.clearSelect();
                })
                .catch((err) => "");
        }
        onMounted(() => {
            getAuthGroupList();
            getRolesList();
            getList();
        });
        return {
            UIAuth,
            bodySize,
            ...toRefs(state),
            elForm,
            pTableTree,
            rowClick,
            rowClear,
            dialogClose,
            selectionChange,
            authGroupGetRolesList,
            getAuthGroupList,
            getRolesList,
            getAuthGroupTitle,
            showAdd,
            getList,
            add,
            showEdit,
            edit,
            setDefault,
            del,
        };
    },
});
</script>

<style scoped lang="scss">
.branch-default-icon {
    // &-title {}
    &-icon {
        background-color: #dd04ed;
        color: #ffffff;
        font-size: 12px;
        padding: 1px 3px;
        border-radius: 3px;
        margin-left: 5px;
    }
}
</style>